package com.lej.dataservice.club.http.interceptor

import com.lej.core.BuildConfig
import com.lej.core.common.*
import com.lej.core.utils.MMKVUtils
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.ResponseBody.Companion.toResponseBody
import okio.Buffer
import java.io.IOException


/**
 * 添加公共参数token
 */
class ParamsInterceptor : Interceptor {
    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val oldRequest = chain.request()
        val newRequestBuild: Request.Builder?
        val method = oldRequest.method
        var postBodyString = ""
        if ("POST" == method) {
            when (val oldBody = oldRequest.body) {
                is FormBody -> {
                    val formBody = FormBody.Builder().apply {
                        getCommParams().forEach { add(it.key, it.value) }
                    }.build()

                    newRequestBuild = oldRequest.newBuilder()

                    postBodyString = bodyToString(oldRequest.body)
                    postBodyString += (if (postBodyString.isNotEmpty()) "&" else "") +
                            bodyToString(formBody)
                    newRequestBuild.post(
                        postBodyString.toRequestBody("application/x-www-form-urlencoded;charset=UTF-8".toMediaTypeOrNull())
                    )
                }
                is MultipartBody -> {
                    val oldBodyMultipart: MultipartBody = oldBody
                    val oldPartList = oldBodyMultipart.parts
                    val builder = MultipartBody.Builder()
                    builder.setType(MultipartBody.FORM)
                    val requestBody1 = PCacheInfo.token
                        .toRequestBody("text/plain".toMediaTypeOrNull())
                    val requestBody2 = "1".toRequestBody("text/plain".toMediaTypeOrNull())
                    val requestBody3 = BuildConfig.VERSION_CODE.toString()
                        .toRequestBody("text/plain".toMediaTypeOrNull())
                    val requestBody4 = MMKVUtils.getInstance().getString(LOCATION)
                        .toRequestBody("text/plain".toMediaTypeOrNull())

                    val requestBody5 = PCacheInfo.uuid
                        .toRequestBody("text/plain".toMediaTypeOrNull())

                    for (part in oldPartList) {
                        builder.addPart(part)
                        postBodyString += bodyToString(part.body) + "\n"
                    }
                    builder.addPart(requestBody1)
                    postBodyString += bodyToString(requestBody1) + "\n"

                    builder.addPart(requestBody2)
                    postBodyString += bodyToString(requestBody2) + "\n"

                    builder.addPart(requestBody3)
                    postBodyString += bodyToString(requestBody3) + "\n"
                    builder.addPart(requestBody4)
                    postBodyString += bodyToString(requestBody4) + "\n"
                    builder.addPart(requestBody5)
                    postBodyString += bodyToString(requestBody5) + "\n"

                    newRequestBuild = oldRequest.newBuilder()
                    newRequestBuild.post(builder.build())
                }
                else -> newRequestBuild = oldRequest.newBuilder()
            }
        } else {
            // 添加新的参数
            val commonParamsUrlBuilder = oldRequest.url
                .newBuilder()
                .scheme(oldRequest.url.scheme)
                .host(oldRequest.url.host)
                .apply { getCommParams().forEach { addQueryParameter(it.key, it.value) } }
                .build()
            newRequestBuild = oldRequest.newBuilder()
                .method(oldRequest.method, oldRequest.body)
                .url(commonParamsUrlBuilder)
        }
        val newRequest = newRequestBuild
            .addHeader("Accept", "application/json")
            .addHeader("Accept-Language", "zh")
            .build()

        val response = chain.proceed(newRequest)
        val mediaType = response.body!!.contentType()
        val content = response.body!!.string()
        return response.newBuilder()
            .body(content.toResponseBody(mediaType))
            .build()
    }

    private fun bodyToString(request: RequestBody?): String {
        try {
            if (request == null) return ""
            return Buffer().apply { request.writeTo(this) }.readUtf8()
        } catch (e: IOException) {
            return "did not work"
        }
    }


    companion object {
        fun getCommParams() : Map<String, String> {
            return HashMap<String, String>().apply {
//                put(TOKEN, PCacheInfo.token)
//                put(OS, "1")//1代表Android设备
//                put(VERSION, BuildConfig.VERSION_CODE.toString())
//                put(LOCATION, MMKVUtils.getInstance().getString(LOCATION))
//                put(HTTP_UUID, PCacheInfo.uuid)
//                put(OAID, PCacheInfo.oaid)
            }
        }
    }
}
